<template>
  <div class="listWapper">
    <customDetailsTopbar title="集团能耗分析" flag :show-right-icon="true" @back="back">
      <template #right>
        <i class="iconfont mr-1" @click="openSuperSearch">&#xe6aa;</i>
      </template>
    </customDetailsTopbar>
    <div class="listInner px-1">
      <div class="common_list">
        <customTitle :is-line="true" bg-color="#3795ff" title="能源消费量（万吨标准煤）时间变化分析" />
        <div ref="timeAnalysis" class="timeAnalysis" style="height: 250px;" />
        <customTitle :is-line="true" bg-color="#3795ff" title="用能结构占比分析" />
        <div ref="proportionAnalysis" class="proportionAnalysis" style="height: 250px;" />
        <customTitle :is-line="true" bg-color="#3795ff" title="不同行业单位产值综合能耗分析（吨标准煤/万元）" />
        <div ref="energyAnalysis" class="energyAnalysis" style="height: 250px;" />
      </div>
    </div>

    <van-popup v-model="superSearch" position="right" :style="{ width: '90%', height: '100%' }" lock-scroll close-on-popstate closeable class="custom-van-pop">
      <div class="pop-vertical-flex">
        <div class="pop-content">
          <custom-timer type="year" title="所属年份" :is-interval="false" :is-clear="false" :date-value.sync="form.years" placeholder="请选择所属年份" />
          <customPopCascade ref="customPopCascade" title="行政区划" cascader-title="行政区划" :field-names="cascadeDistrict.fieldNames" :check-value.sync="form.districtCode" :list="cascadeDistrict.district" @change="cascadeDistrictChange" @clearData="form.districtCode = ''" />
        </div>
        <div class="pop-bottom">
          <van-button type="default" @click="resetSuperSearch">清空</van-button>
          <van-button type="info" @click="handleSuperSearch">确认</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { lineChart, pieChart } from '@/utils/chart.js'
import commonList from '@/assets/mixin/commonList'
import { parseTime } from '@/utils'
import { getDistrict } from '@/api/common'
import { getByquarter, getEnergyUsage, getIndustry } from '@/api/commonPage/energyConsumption'

export default {
  mixins: [commonList],
  inject: ['layout'],
  data() {
    return {
      form: {
        companyId: -1,
        districtCode: '',
        // industryType: '',
        years: new Date().getFullYear() + ''
      },
      currenTime: parseTime(new Date(), '{y}'),
      areaList: [
        { label: '四川', value: '四川' },
        { label: '北京', value: '北京' },
        { label: '陕西', value: '陕西' }
      ],
      apiNum: 0,
      loadNum: 0,
      cascadeDistrict: {
        district: [], // 行政区划
        fieldNames: {
          text: 'name',
          value: 'code',
          children: 'subList'
        }
      }
    }
  },
  mounted() {
    this.getData()
    this.getDistrict()
  },
  methods: {
    getData() {
      this.layout.showLoading()
      this.getByquarter()
      this.getEnergyUsage()
      this.getIndustry()
    },
    closeLoading() {
      this.loadNum++
      if (this.apiNum <= this.loadNum) {
        this.layout.hideLoading()
      }
    },
    async getByquarter() {
      this.layout.showAreaLoading(['.timeAnalysis'])
      // 先清除之前的数据，避免图例排序颠倒
      this.initTimeAnalysis([{ name: '', years: '', lastq: '', currentq: '' }])
      this.apiNum++
      const { data, status } = await getByquarter(this.form)
      if (data && status === 0) {
        this.initTimeAnalysis(data)
      }
      this.layout.hideAreaLoading(['.timeAnalysis'])
      this.closeLoading()
    },
    async getEnergyUsage() {
      this.layout.showAreaLoading(['.proportionAnalysis'])
      this.apiNum++
      const { data, status } = await getEnergyUsage(this.form)
      if (data && status === 0) {
        this.proportionAnalysis(data)
      }
      this.layout.hideAreaLoading(['.proportionAnalysis'])
    },
    async getIndustry() {
      this.layout.showAreaLoading(['.energyAnalysis'])
      this.apiNum++
      const { data, status } = await getIndustry(this.form)
      if (data && status === 0) {
        this.energyAnalysis(data)
      }
      this.layout.hideAreaLoading(['.energyAnalysis'])
    },
    back() {
      this.$router.push({
        path: '/staging/monitor',
        query: { ...this.$route.query }
      })
    },
    initTimeAnalysis(data) {
      const dataX = data.map(val => val.name)
      const lastYear = data[0]?.years === undefined ? (this.form.years - 1 + '年') : ''
      const year = data[0]?.years === undefined ? (this.form.years + '年') : ''
      const dataSeries = [
        {
          name: lastYear,
          type: 'line',
          data: data.map(val => val.lastq),
          itemStyleColor: '#6298F5',
          lineStyleColor: '#6298F5',
          smooth: true
        },
        {
          name: year,
          type: 'line',
          data: data.map(val => val.currentq),
          itemStyleColor: '#5ED9A8',
          lineStyleColor: '#5ED9A8',
          smooth: true
        }
      ]
      const params = {
        legendShow: true,
        tooltipShow: true,
        gridRight: '5%',
        gridTop: '12%',
        gridLeft: '0%',
        gridBottom: '8%',
        // rotate: 40,
        legendBottom: '0',
        tooltipFormatter: function(arr) {
          let str = arr[0].axisValue + '<br>'
          arr.forEach(item => {
            str += item.marker + item.seriesName + '：' + item.value + '<br>'
          })
          return str
        }
      }
      const chart = this.$refs.timeAnalysis
      if (chart) {
        if (data.length > 0) {
          const myChart = this.$echarts.init(chart)
          myChart.setOption(lineChart(dataX, dataSeries, params))
          window.addEventListener('resize', () => {
            myChart.resize()
          })
        } else {
          this.layout.chartNoData(chart)
        }
      }
    },
    proportionAnalysis(params) {
      const data = params.filter(item => {
        return item.name !== '能源消费量' && item.name !== '用能结构占比'
      })
      console.log('data', data)
      const totalNum = data.reduce((previousValue, currentValue, currentIndex, array) => previousValue + Number(currentValue.currentq), 0)
      const currentq = params.find(val => val.name === '用能结构占比')?.currentq
      const chart = this.$refs.proportionAnalysis
      const colors = ['#5B8FF9', '#52D6A2', '#5D7092', '#F5BB0E', '#6F5EF9']
      const options = pieChart(
        {
          legendShow: false,
          legendBottom: 0,
          // legendRight: 'center',
          tooltipShow: true,
          titleShow: true,
          titleText: currentq + '万吨标准煤',
          titleX: '',
          titleY: '0%',
          titleColor: '#333',
          tooltipFormatter: (params) => {
            return `${params.seriesName}<br/>${params.marker}${params.name}：${params.value}(${params.percent}%)<br/>`
          }
        },
        [
          {
            type: 'pie',
            name: '用能结构分析',
            radius: '60%',
            // radius: ['55%', '75%'],
            center: ['50%', '53%'],
            data: data.map(val => ({
              name: val.name,
              value: val.currentq,
              label: {
                color: '#333',
                position: 'outside',
                formatter: (params) => {
                  const data = params.data
                  if (Number(data.value) === 0) {
                    data.labelLine = { show: false }
                    data.label.show = false
                  } else {
                    return `${params.percent}%`
                  }
                  return `${params.percent}%`
                }
              }
            })),
            percentPrecision: 3
          }
        ],
        colors
      )
      options.legend.icon = 'circle'
      if (chart) {
        if (totalNum !== 0) {
          const myChart = this.$echarts.init(chart)
          myChart.setOption(options)
          this.setLegend(chart, myChart)
          window.addEventListener('resize', () => {
            myChart.resize()
          })
        } else {
          this.layout.chartNoData(chart)
        }
      }
    },
    energyAnalysis(data) {
      const dataX = data.map(val => val.name)
      const dataSeries = [
        {
          name: '万元产值综合能耗',
          type: 'bar',
          data: data.map(val => val.comprehensiveConsumption),
          itemStyleColor: '#6395F9',
          lineStyleColor: '#6395F9'
        },
        {
          name: '万元增加值综合能耗',
          type: 'bar',
          data: data.map(val => val.comprehensiveAddConsumption),
          itemStyleColor: '#5BD4A7',
          lineStyleColor: '#5BD4A7'
        },
        {
          name: '行业均值',
          type: 'bar',
          data: data.map(val => val.meanValue),
          itemStyleColor: '#657798',
          lineStyleColor: '#657798'
        }
      ]
      const params = {
        legendShow: false,
        gridRight: '5%',
        gridTop: '10%',
        gridLeft: '0%',
        gridBottom: '10%',
        rotate: 40,
        legendBottom: '0',
        tooltipShow: true,
        tooltipFormatter: function(arr) {
          let str = arr[0].axisValue + '<br>'
          arr.forEach(item => {
            str += item.marker + item.seriesName + '：' + item.value + '<br>'
          })
          return str
        },
        legendFormatter: function(name) {
          return name.length > 5 ? (name.slice(0, 5) + '...') : name
        }
      }
      const chart = this.$refs.energyAnalysis
      if (chart) {
        if (data.length > 0) {
          const myChart = this.$echarts.init(chart)
          const options = lineChart(dataX, dataSeries, params)
          myChart.setOption(options)
          this.setLegend(chart, myChart)
          window.addEventListener('resize', () => {
            myChart.resize()
          })
        } else {
          this.layout.chartNoData(chart)
        }
      }
    },
    resetSuperSearch() {
      this.$refs.customPopCascade?.clearCascader()
      this.form.districtCode = ''
      this.form.industryType = ''
    },
    handleSuperSearch() {
      this.superSearch = false
      this.getData()
    },
    // 获取行政区划
    async getDistrict() {
      const { data, status } = await getDistrict()
      if (data && status === 0) {
        this.cascadeDistrict.district = this.removerEmpty(data, 'subList')
      }
    },
    // 行政区划链接框改变
    cascadeDistrictChange({ value, selectedOptions, tabIndex }) {
      this.form.districtCode = value
    },
    // 回调去除空白子集
    removerEmpty(data, listName) {
      if (data.length) {
        data.forEach(item => {
          if (item[listName] && item[listName].length) {
            item[listName] = this.removerEmpty(item[listName], listName)
          } else {
            delete item[listName]
          }
        })
      }
      return data
    }
  }
}
</script>

<style lang="scss" scoped>
.checkbox-title {
    font-size: 28px;
    font-weight: bold;
    margin-bottom: 30px;
  }
</style>
